<script setup lang="ts">
import CustomNavbar from '@/pages/index/components/CustomNavbar.vue'
import CategoryPanel from '@/pages/index/components/CategoryPanel.vue'
import Skeleten from '@/pages/index/components/Skeleten.vue'
import HotPanel from '@/pages/index/components/HotPanel.vue'
import { onLoad } from '@dcloudio/uni-app'
import { getHomeBanner, getHomeCategory, getHomeHot } from '@/api/home'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'

import CommonGuess from '@/components/CommonGuess.vue'
import type { CommonGuessInstance } from '@/components/components'

// 获取轮播图数据
const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBanner(1)
  bannerList.value = res.result
}

// 获取分类数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategory()
  categoryList.value = res.result
}

// 获取热门推荐数据
const hotList = ref<HotItem[]>([])
const getHomeHotData = async () => {
  const res = await getHomeHot()
  hotList.value = res.result
}

// 标记是否显示骨架屏
const isLoading = ref(true)

// 小程序加载页面生命周期函数
onLoad(async () => {
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
})

// 获取模板ref
const guess = ref<CommonGuessInstance>()

const onScrolltolower = () => {
  guess.value?.loadMore()
}

// 下拉刷新标记
const isRefreshing = ref(false)

// 下拉刷新
const onRefresh = async () => {
  // 触发下拉修改标记
  isRefreshing.value = true

  guess.value?.resetData(),
    // 重新获取数据，使用promise.all等待所有数据获取完成，提升性能
    await Promise.all([
      getHomeBannerData(),
      getHomeCategoryData(),
      getHomeHotData(),
      guess.value?.loadMore(),
    ])
  isRefreshing.value = false
}
</script>

<template>
  <CustomNavbar />
  <scroll-view
    refresher-enabled
    :refresher-triggered="isRefreshing"
    @refresherrefresh="onRefresh"
    @scrolltolower="onScrolltolower"
    class="my-scroll"
    scroll-y
  >
    <!-- 骨架屏 -->
    <Skeleten v-if="isLoading" />
    <template v-else>
      <CommonSwiper :list="bannerList" />
      <CategoryPanel :list="categoryList" />
      <HotPanel :list="hotList" />
      <CommonGuess ref="guess" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  display: flex;
  height: 100%;
  flex-direction: column;
}

.my-scroll {
  flex: 1;
}
</style>
